 //
//  RBCommentPhotoSelectView.m
//  WaitBuyer
//
//  Created by Lan on 2018/10/12.
//  Copyright © 2018年 SummerTea. All rights reserved.
//

#import "RBGrowablePhotoContainer.h"
#import "TZImagePickerController.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import <Masonry.h>
#import <UIView+YYAdd.h>
#import "TZPhotoPreviewController.h"
#import "RBPhotoBrowser.h"
#import <UIImage+YYAdd.h>
#import "UIImageView+RBAdd.h"
#import "UIViewController+RBAdd.h"
#import <UIColor+YYAdd.h>

@interface RBGrowablePhotoSelectCell : UICollectionViewCell

@property(nonatomic, strong) UIImageView *imgView;
@property(nonatomic, strong) UIImageView *deleteImgView;
@property(nonatomic, copy) void(^deleteBlock)(NSInteger index);
@property(nonatomic, assign) BOOL editable;

@end

@implementation RBGrowablePhotoSelectCell

- (UIImageView *)imgView
{
    if (!_imgView)
    {
        self.imgView = ({
            UIImageView *view = [UIImageView new];
            view.contentMode = UIViewContentModeScaleAspectFill;
            view.clipsToBounds = YES;
            [self.contentView addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            view;
        });
    }
    return _imgView;
}

- (void)setEditable:(BOOL)editable
{
    _editable = editable;
    [self.contentView rbSetCornerRadius:7];
    self.imgView.hidden = NO;
    if (editable)
    {
        self.deleteImgView.hidden = NO;
    }
    else
    {
        _deleteImgView.hidden = YES;
    }
}

- (UIImageView *)deleteImgView
{
    if (!_deleteImgView)
    {
        self.deleteImgView = ({
            UIImageView *view = [UIImageView new];
            view.contentMode = UIViewContentModeScaleAspectFit;
            view.clipsToBounds = YES;
            [view setResponseArea:UIEdgeInsetsMake(12, 12, 12, 12)];
            [view rbAddTapGesWithTarget:self action:@selector(deleteViewTapped)];
            [self.contentView addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.top.mas_equalTo(0);
                make.height.mas_equalTo(20);
                make.width.mas_equalTo(40);
            }];
            
            //text
            UILabel *label = [UILabel new];
            [view addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            label.font = [UIFont systemFontOfSize:13];
            label.text = @"删除";
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor colorWithHexString:@"666666"];
            label.backgroundColor = [UIColor colorWithHexString:@"eeeeee"];
            
            view;
        });
    }
    return _deleteImgView;
}

- (void)deleteViewTapped
{
    if (self.deleteBlock)
    {
        self.deleteBlock(self.tag);
    }
}

@end

@interface RBGrowablePhotoContainer()<TZImagePickerControllerDelegate, RBPhotoDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, strong)NSMutableArray *photos;
@property(nonatomic, assign) CGFloat viewHeight;

@property(nonatomic, assign) NSInteger maxNum;
@property(nonatomic, assign) NSInteger colNum;
@property(nonatomic, assign) BOOL editable;
@property(nonatomic, assign) CGFloat viewWidth;
@property(nonatomic, assign) CGFloat itemH;

@property(nonatomic, strong) RBPhotoBrowser *photoBrowser;

@property(nonatomic, strong) UICollectionView *collectionView;

@end

@implementation RBGrowablePhotoContainer

#pragma mark - System


#pragma mark - Private

- (void)layout
{
    NSInteger max = self.maxNum;
    NSInteger totalCount = MIN(max, self.photos.count + 1);
    if (!self.editable)
    {
        totalCount --;
    }
    
    NSInteger col = self.colNum;
    CGFloat itemW = (self.viewWidth - 15*(col - 1))/col;
    if (self.itemH <= 0)
    {
        self.itemH = itemW;
    }
    
    NSInteger row = ((NSInteger)ceilf(totalCount/(1.0*col)));
    CGFloat height = (15 + self.itemH)*row - 15;
    
    self.viewHeight = height;
    [self.collectionView reloadData];
}

#pragma mark - Public

+ (instancetype)viewWithMaxNum:(NSInteger)maxNum colNum:(NSInteger)colNum editable:(BOOL)editable viewWidth:(CGFloat)viewWidth itemH:(CGFloat)itemH
{
    RBGrowablePhotoContainer *view = [RBGrowablePhotoContainer new];
    view.maxNum = maxNum;
    view.colNum = colNum;
    view.editable = editable;
    view.viewWidth = viewWidth;
    view.itemH = itemH;
    [view layout];
    return view;
}

+ (instancetype)viewWithMaxNum:(NSInteger)maxNum colNum:(NSInteger)colNum editable:(BOOL)editable viewWidth:(CGFloat)viewWidth
{
    return [self viewWithMaxNum:maxNum colNum:colNum editable:editable viewWidth:viewWidth itemH:0];
}

- (void)addPhotos:(NSArray *)array
{
    if (array.count)
    {
        [self.photos addObjectsFromArray:array];
        [self layout];
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(self.viewHeight);
        }];
    }
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    if (photos.count)
    {
        //1538*922
        for (UIImage *image in photos)
        {
//            CGFloat width = 922;
//            CGFloat height = image.size.height/image.size.width*width;
//            [self.photos addObject:[image imageByResizeToSize:CGSizeMake(width, MIN(height, 1538)) contentMode:UIViewContentModeScaleAspectFill]];
            [self.photos addObject:image];
        }
        
        [self layout];
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(self.viewHeight);
        }];
    }
}

#pragma mark - RBPhotoDelegate

- (void)rbPhoto:(nonnull RBPhotoBrowser *)photo didScrollToIndex:(CGFloat)index withPhotoController: (nonnull RBPhotoViewController *)controller
{
    controller.title = [NSString stringWithFormat:@"%zd/%zd", photo.currentIndex + 1, photo.photoModels.count];
}

#pragma mark - UICollectionViewDataSource & Delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.editable)
    {
        return MIN(self.maxNum, self.photos.count + 1);
    }
    else
    {
        return MIN(self.maxNum, self.photos.count);
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RBGrowablePhotoSelectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.tag = indexPath.row;
    if (indexPath.row >= self.photos.count)
    {
        cell.editable = NO;
        cell.imgView.image = [UIImage imageNamed:@"tianjiazhaopian"];
    }
    else
    {
        cell.editable = self.editable;
        __weak typeof(self) weak_self = self;
        if (self.editable)
        {
            cell.deleteBlock = ^(NSInteger index) {
                [weak_self deletePhotoAtIndex:index];
            };
        }
        id data = self.photos[indexPath.row];
        if ([data isKindOfClass:[UIImage class]])
        {
            UIImage *image = (UIImage *)data;
            cell.imgView.image = image;
        }
        else if ([data isKindOfClass:[NSString class]])
        {
            [cell.imgView setImageWithUrl:(NSString *)data placeHolder:nil];
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.photos.count)
    {
        [self addBtnTapped];
    }
    else
    {
        [self imageViewTappedAtIndex:indexPath.row];
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.row < self.photos.count && self.editable;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath
           toIndexPath:(NSIndexPath *)destinationIndexPath
{
    if (sourceIndexPath.row >= self.photos.count || destinationIndexPath.row >= self.photos.count)
    {
        [self.collectionView moveItemAtIndexPath:destinationIndexPath toIndexPath:sourceIndexPath];
    }
    else
    {
        UIImage *image = self.photos[sourceIndexPath.row];
        [self.photos removeObjectAtIndex:sourceIndexPath.row];
        [self.photos insertObject:image atIndex:destinationIndexPath.row];
    }
}

#pragma mark - Event

- (void)addBtnTapped
{
    TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxNum - self.photos.count delegate:self];
    vc.allowPreview = YES;
    vc.allowPickingGif = NO;
    vc.allowPickingVideo = NO;
    vc.allowPickingOriginalPhoto = NO;
    
    vc.photoWidth = 922;
    
    vc.barItemTextColor = [UIColor blackColor];
    vc.naviTitleColor = [UIColor blackColor];
    vc.navigationBar.tintColor = [UIColor blackColor];
    vc.statusBarStyle = UIStatusBarStyleDefault;
    
    [[self viewController] presentViewController:vc animated:YES completion:nil];
}

- (void)imageViewTappedAtIndex: (NSInteger)index
{
    NSArray *imageViews = ({
        NSMutableArray *arrayM = [NSMutableArray array];
        NSInteger cellCount = [self.collectionView visibleCells].count;
        for (NSInteger i = 0; i < cellCount; i++)
        {
            RBGrowablePhotoSelectCell *cell = (RBGrowablePhotoSelectCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
            [arrayM addObject:cell.imgView];
        }
        arrayM;
    });
    [self.viewController showWithImages:self.photos index:index imageViews:imageViews];
}

- (void)deletePhotoAtIndex: (NSInteger)index
{
    [self.photos removeObjectAtIndex:index];
    [self layout];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.viewHeight);
    }];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress
{
    //获取此次点击的坐标，根据坐标获取cell对应的indexPath
    CGPoint point = [longPress locationInView:self.collectionView];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    //根据长按手势的状态进行处理。
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            //当没有点击到cell的时候不进行处理
            if (!indexPath) {
                break;
            }
            //开始移动
            [_collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
            break;
        case UIGestureRecognizerStateChanged:
            //移动过程中更新位置坐标
            [_collectionView updateInteractiveMovementTargetPosition:point];
            break;
        case UIGestureRecognizerStateEnded:
            //停止移动调用此方法
            NSLog(@"endRow:%zd", indexPath.row);
            if (indexPath.row >= self.photos.count)
            {
                [_collectionView cancelInteractiveMovement];
            }
            else
            {
                [_collectionView endInteractiveMovement];
            }
            break;
        default:
            //取消移动
            [_collectionView cancelInteractiveMovement];
            break;
    }
}

#pragma mark - Setter


#pragma mark - Getter

- (NSMutableArray *)photos
{
    if (!_photos)
    {
        self.photos = [NSMutableArray array];
    }
    return _photos;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        self.collectionView = ({
            UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
            layout.minimumLineSpacing = 15;
            layout.minimumInteritemSpacing = 15;
            layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
            NSInteger col = self.colNum;
            CGFloat itemW = (self.viewWidth - 15*(col - 1))/col - 2;//缩放容易失精度,减2容错一下
            layout.itemSize = CGSizeMake(itemW, self.itemH);
            
            UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
            collectionView.scrollEnabled = NO;
            [self addSubview:collectionView];
            [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            collectionView.dataSource = self;
            collectionView.delegate = self;
            [collectionView registerClass:[RBGrowablePhotoSelectCell class] forCellWithReuseIdentifier:@"cell"];
            collectionView.backgroundColor = [UIColor whiteColor];
            
            UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
            [collectionView addGestureRecognizer:longPressGesture];
            
            collectionView;
        });
    }
    return _collectionView;
}

@end
